package com.example.admindatasource.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.admindatasource.exception.FileException;
import com.example.admindatasource.filepload.FileConstant;
import com.example.admindatasource.mapper.SysUploadFileMapper;
import com.example.admindatasource.model.po.SysUploadFile;
import com.example.admindatasource.model.vo.SysUploadFileVO;
import com.example.admindatasource.service.ISysUploadFileService;
import com.example.adminframework.constant.ErrorCode;
import com.example.adminframework.constant.HttpCode;
import com.example.adminframework.constant.Status;
import com.example.adminframework.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class SysUploadFileServiceImpl extends ServiceImpl<SysUploadFileMapper, SysUploadFile> implements ISysUploadFileService {

    private static final Logger log = LoggerFactory.getLogger(SysUploadFileServiceImpl.class);

    @Override
    public SysUploadFileVO fileUpload(String module, MultipartFile file) {
        if (ObjectUtils.isEmpty(file) || file.isEmpty()) {
            throw new FileException(HttpCode.BAD_REQUEST, ErrorCode.PARAMETER_IS_NULL);
        }
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        //例如  jpg
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String type = file.getContentType();
        long size = file.getSize();
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String parentPathRelative = FileConstant.uploads + File.separator + module + File.separator + time;
        String storePathRelative = parentPathRelative + File.separator + uuid + "." + fileSuffix;
        File parentFile = new File(FileConstant.STORE_PATH + File.separator + parentPathRelative);
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        File dest = new File(FileConstant.STORE_PATH + File.separator + storePathRelative);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            log.error("文件上传错误 {}", e.getMessage());
            throw new FileException(HttpCode.INTERNAL_SERVER_ERROR, ErrorCode.UN_KNOWN_ERROR);
        }
        //文件上传成功后 相关文件信息入库
        return saveRecord(module, originalFilename, uuid, type, time, storePathRelative, size);
    }


    /**
     * 保存文件基本信息
     * @return
     */
    private SysUploadFileVO saveRecord(String module, String originalFilename, String uuid, String type, String time, String storePathRelative, long size) {
        SysUploadFile sysUploadFile = new SysUploadFile();
        sysUploadFile.setFileName(uuid);
        sysUploadFile.setOriginFileName(originalFilename);
        sysUploadFile.setSize(size);
        //请求地址
//        sysUploadFile.setLocation(FileConstant.requestLocationPrefix + uuid+"."+type);
        sysUploadFile.setLocation(FileConstant.requestLocationPrefix + module + File.separator + time + File.separator + uuid + "." + type);
        //上传地址 相对路径
        sysUploadFile.setFilePath(storePathRelative);
        sysUploadFile.setType(type);
        sysUploadFile.setCreateTime(LocalDateTime.now());
        // 获取创建用户id
//        sysUploadFile.setCreateId(JwtTokenUtil.getUserTokenBySession().getUserID());
//        sysUploadFile.setModule(module);
        sysUploadFile.setStatus(Status.NORMAL.getValue());

        try {
            save(sysUploadFile);
        } catch (Exception e) {
            log.error("文件表新增出错 {}", e.getMessage());
            throw new FileException(HttpCode.INTERNAL_SERVER_ERROR, ErrorCode.JDBC_ADD_ERROR);
        }
        //SysUploadFile-->SysUploadFileVO
        SysUploadFileVO vo = new SysUploadFileVO();
        CopyUtil.copyProperties(sysUploadFile, vo);
        return vo;
    }

}
